package com.byd.base;

import java.lang.ref.SoftReference;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import com.byd.utils.Lg;

public abstract class BaseDialogFragment<T extends BaseDialogAction> extends DialogFragment {
	protected Context mContext;
	protected Resources mRes;
	protected SoftReference<View> mCacheView;
	private int mAnimId = -1;
	private Point mPoint;
	private int mGravity = Gravity.CENTER;
	/** 瀵硅瘽妗嗗垰鍑烘潵鏃跺墠涓�娈垫椂闂达紝涓嶈兘鐐瑰嚮瀵硅瘽妗嗗閮ㄤ娇瀵硅瘽妗嗘秷澶憋紝闃叉棰戠箒鐨勬樉绀哄拰闅愯棌瀵硅瘽妗� */
	private int mUnTouchcancelTime = -1;
	private boolean mCanceledOnTouchOutside = true;
	private FragmentManager mFragmentManager;
	private final Handler mHandler = new Handler(Looper.getMainLooper());
	private boolean mAdded;
	private T mAction;

	public BaseDialogFragment() {
		super();
		v("new instance");
	}

	private String getTagStr() {
		return Lg.BASE_TAG + getClass().getSimpleName();
	}

	protected void v(Object msg) {
		Lg.v(getTagStr(), msg);
	}

	protected void d(Object msg) {
		Lg.d(getTagStr(), msg);
	}

	protected void i(Object msg) {
		Lg.i(getTagStr(), msg);
	}

	protected void w(Object msg) {
		Lg.w(getTagStr(), msg);
	}

	protected void e(Object msg) {
		Lg.e(getTagStr(), msg);
	}

	protected void wtf(Object msg) {
		Lg.wtf(getTagStr(), msg);
	}

	public void init(FragmentManager manager, T action) {
		mFragmentManager = manager;
		mAction = action;
	}

	/** 杩斿洖甯冨眬鏂囦欢ID */
	protected abstract int onInflateView();

	/** 鍥犱负瀵硅瘽妗嗙殑瀹藉害涓嶈兘鏍规嵁甯冨眬璁剧疆瀹藉害銆� 濡傛灉瀵硅瘽妗嗙殑瀹藉害鏄牴鎹煇寮犲浘鐗囨潵閫傚簲鐨勶紝鍒欒繑鍥炴鍥剧墖 */
	protected int onMeasureWidth() {
		return 0;
	}

	/** 濡傛灉瀵硅瘽妗嗙殑瀹藉害鏄牴鎹睆骞曟潵閫傞厤鐨勶紝姝よ繑鍥炲睆骞曠殑姣斾緥 */
	protected int onMeasureWidthPercent() {
		return 0;
	}

	protected int onMeasureHeightPercent() {
		return 0;
	}

	/** View宸插垱寤哄畬姣曪紝寤鸿鍦ㄦ鍒濆鍖朧iew鎴栨敞鍐屼簨浠剁瓑銆� <br>
	 * 鏈柟娉曚笉鏄瘡娆℃樉绀烘椂閮戒細璋冪敤锛岃�屾槸姣忔鍒涘缓View鐨勬椂鍊欐墠璋冪敤銆� */
	protected abstract void onCreateView();

	/** Dialog寮�濮嬫樉绀猴紝寤鸿鍦ㄦ澶勬帶鍒禫iew銆� 鏈柟娉曟瘡娆℃樉绀烘椂閮戒細璋冪敤 */
	protected abstract void onShowDialog();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = getActivity().getBaseContext();
		mRes = mContext.getResources();
	}

	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		final Dialog dialog = super.onCreateDialog(savedInstanceState);
		if(mAnimId > 0) {
			dialog.getWindow().setWindowAnimations(mAnimId);
		}
		return dialog;
	}

	@Override
	public void onStart() {
		super.onStart();
		final Dialog dialog = getDialog();
		int width = 0;
		if((width = onMeasureWidth()) > 0) {
			dialog.getWindow().setLayout(width, ViewGroup.LayoutParams.WRAP_CONTENT);
		}
		else {
			final int w = onMeasureWidthPercent();
			final int h = onMeasureHeightPercent();
			final DisplayMetrics metrics = getResources().getDisplayMetrics();
			if(w > 0) {
				width = w * metrics.widthPixels / 100;
			}
			else {
				width = ViewGroup.LayoutParams.WRAP_CONTENT;
			}
			final int height;
			if(h > 0) {
				height = h * metrics.heightPixels / 100;
			}
			else {
				height = ViewGroup.LayoutParams.WRAP_CONTENT;
			}
			dialog.getWindow().setLayout(width, height);
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = getContentView();
		if(view == null) {
			view = inflater.inflate(onInflateView(), null);
			mCacheView = new SoftReference<View>(view);
			onCreateView();
		}
		if(mPoint != null) {
			final LayoutParams params = getDialog().getWindow().getAttributes();
			params.gravity = mGravity;
			params.x = mPoint.x;
			params.y = mPoint.y;
			params.width = 1024;
			params.height = android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
			getDialog().getWindow().setAttributes(params);
		}
		setBackgroundColor(Color.TRANSPARENT);
		getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
		if(mUnTouchcancelTime < 0) {
			mUnTouchcancelTime = 500;
		}
		if(mCanceledOnTouchOutside) {
			getDialog().setCanceledOnTouchOutside(false);
			postSingleDelayed(mTouchCancel, mUnTouchcancelTime);
		}
		else {
			getDialog().setCanceledOnTouchOutside(false);
		}
		onShowDialog();
		return view;
	}

	public T getAction() {
		return mAction;
	}

	/** 瀵硅瘽妗嗗垰鍑烘潵鏃跺墠涓�娈垫椂闂达紝涓嶈兘鐐瑰嚮瀵硅瘽妗嗗閮ㄤ娇瀵硅瘽妗嗘秷澶憋紝闃叉棰戠箒鐨勬樉绀哄拰闅愯棌瀵硅瘽妗� */
	public void setUnTouchcancelTime(int timeMillis) {
		mUnTouchcancelTime = Math.max(timeMillis, 0);
		postSingleDelayed(mTouchCancel, mUnTouchcancelTime);
	}

	/** 寤惰繜涓�娈垫椂闂村悗鑷姩闅愯棌Dialog */
	public void delayDismiss(int delayMillis) {
		postSingleDelayed(mHide, delayMillis);
	}

	/** 鍙栨秷涔嬪墠璁剧疆鐨勫欢杩熻嚜鍔ㄩ殣钘廌ialog */
	public void cancelDelayDismiss() {
		removeCallbacks(mHide);
	}

	/** 璁剧疆鐐瑰嚮Dialog澶栭潰鍖哄煙鏄惁闅愯棌Dialog */
	public void setCanceledOnTouchOutside(boolean cancel) {
		mCanceledOnTouchOutside = cancel;
		if(!cancel) {
			removeCallbacks(mTouchCancel);
		}
	}

	/** 璁剧疆Dialog鑳屾櫙棰滆壊 */
	protected void setBackgroundColor(int color) {
		getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(color));
	}

	/** 璁剧疆Dialog鑳屾櫙 */
	protected void setBackground(Drawable drawable) {
		getDialog().getWindow().setBackgroundDrawable(drawable);
	}

	/** 璁剧疆Dialog鑳屾櫙 */
	protected void setBackgroundResource(int resid) {
		getDialog().getWindow().setBackgroundDrawableResource(resid);
	}

	/** 璁剧疆Dialog鏄剧ず鏃讹紝涓嬪眰鐣岄潰鏄惁闇�瑕佸彉鏆� */
	protected void setBackgroundDark(boolean dark) {
		final LayoutParams params = getDialog().getWindow().getAttributes();
		if(dark) {
			getDialog().getWindow().addFlags(LayoutParams.FLAG_DIM_BEHIND);
		}
		else {
			getDialog().getWindow().clearFlags(LayoutParams.FLAG_DIM_BEHIND);
		}
		params.dimAmount = dark ? 1f : 0;
		getDialog().getWindow().setAttributes(params);
	}

	/** 璁剧疆Dialog鏄剧ず鍜岄��鍑烘椂鐨勫姩鐢绘晥鏋� */
	public void setWindowAnimations(int resId) {
		mAnimId = resId;
		if(getDialog() != null && getDialog().getWindow() != null) {
			getDialog().getWindow().setWindowAnimations(mAnimId);
		}
	}

	/** 鏄剧ずDialog锛� 榛樿Gravity涓篊enter */
	public void show(int x, int y) {
		show(Gravity.CENTER, x, y);
	}

	/** 鏄剧ずDialog */
	public void show(int gravity, int x, int y) {
		mGravity = gravity;
		if(mPoint == null) {
			mPoint = new Point(x, y);
		}
		else {
			mPoint.set(x, y);
		}
		show();
	}

	/** 鏄剧ずDialog锛� 榛樿Gravity涓篊enter */
	public void show() {
		if(mFragmentManager != null && !isAdded() && !mAdded) {
			mAdded = true;
			show(mFragmentManager, getClass().getName());
		}
	}

	@Override
	public void dismiss() {
		super.dismiss();
		if(mFragmentManager != null && isAdded() && mAdded) {
			mAdded = false;
			final FragmentTransaction ft = mFragmentManager.beginTransaction();
			ft.remove(this);
			ft.commit();
		}
	}

	protected final View getContentView() {
		if(mCacheView != null) {
			return mCacheView.get();
		}
		return null;
	}

	@Override
	public void onDestroy() {
		mAdded = false;
		super.onDestroy();
		mContext = null;
		mHandler.removeCallbacksAndMessages(null);
		final View view = getContentView();
		if(view != null) {
			final ViewGroup group = (ViewGroup) view.getParent();
			group.removeView(view);
		}
	}

	public final void setVisibility(int visibility) {
		final View view = getContentView();
		if(view != null) {
			view.setVisibility(visibility);
		}
	}

	protected final View findViewById(int id) {
		final View view = getContentView();
		if(view != null) {
			return view.findViewById(id);
		}
		return null;
	}

	public final int getColor(int id) {
		return getResources().getColor(id);
	}

	public boolean getBoolean(int id) {
		return getResources().getBoolean(id);
	}

	public final float getDimension(int id) {
		return getResources().getDimension(id);
	}

	public final int getDimensionPixelOffset(int id) {
		return getResources().getDimensionPixelOffset(id);
	}

	public final int getDimensionPixelSize(int id) {
		return getResources().getDimensionPixelSize(id);
	}

	public final Drawable getDrawable(int id) {
		return getResources().getDrawable(id);
	}

	public final String[] getStringArray(int id) {
		return getResources().getStringArray(id);
	}

	public final int getInteger(int id) {
		return getResources().getInteger(id);
	}

	public final int[] getIntArray(int id) {
		return getResources().getIntArray(id);
	}

	public final DisplayMetrics getDisplayMetrics() {
		return getResources().getDisplayMetrics();
	}

	public final Configuration getConfiguration() {
		return getResources().getConfiguration();
	}

	private final Runnable mTouchCancel = new Runnable() {
		@Override
		public void run() {
			if(getDialog() != null && mCanceledOnTouchOutside) {
				getDialog().setCanceledOnTouchOutside(true);
			}
		}
	};
	private final Runnable mHide = new Runnable() {
		@Override
		public void run() {
			dismiss();
		}
	};

	public final boolean post(Runnable r) {
		return mHandler.post(r);
	}

	public final boolean postSingle(Runnable r) {
		mHandler.removeCallbacks(r);
		return mHandler.post(r);
	}

	public final boolean postDelayed(Runnable r, long delayMillis) {
		return mHandler.postDelayed(r, delayMillis);
	}

	public final boolean postSingleDelayed(Runnable r, long delayMillis) {
		mHandler.removeCallbacks(r);
		return mHandler.postDelayed(r, delayMillis);
	}

	public final void removeCallbacks(Runnable r) {
		mHandler.removeCallbacks(r);
	}

	@Override
	protected void finalize() throws Throwable {
		i("finalize: " + toString());
		super.finalize();
	}
}
